#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import uuid

from common.logger import Logger
from db2.comm.constant import DB2Type
from db2.comm.error_code import Db2ErrCode
from db2.comm.param_parse import Param
from db2.comm.util.common_util import Db2CommonUtil

LOGGER = Logger().get_logger(filename="db2.log")


class TableSpaces:
    def __init__(self, pid, param: Param):
        self.pid = pid
        self.context = param
        self.instance = self.context.application
        self.username = param.app_auths_key
        self.database_name = self.instance.get("name")
        self.database_id = self.instance.get("id")
        self.instance_name = self.instance.get("parentName")

    def list_for_tablespaces(self):
        LOGGER.info(f"Begin to get db2 table spaces from  pid :{self.pid}")
        table_spaces_list = []
        try:
            table_space_list = Db2CommonUtil.get_table_space_info_dict_of_db(self.username, self.database_name)
        except Exception as ex:
            LOGGER.info(f"Execute cmd failed! exception is {ex}")
            error_message = "Query table spaces failed !"
            LOGGER.error(error_message)
            exception = dict()
            exception["code"] = Db2ErrCode.ERR_DATABASE_STATUS
            exception["message"] = error_message
            params = {"resourceList": table_spaces_list, "exception": exception}
            return params
        for table_space in table_space_list:
            table_space_uuid = str(uuid.uuid5(uuid.NAMESPACE_X500, self.instance.get("id") + DB2Type.DB2TABLESPACE
                                              + self.instance.get("name") + table_space))
            resource = dict()
            resource["id"] = table_space_uuid
            resource["type"] = DB2Type.TYPE
            resource["subType"] = DB2Type.DB2TABLESPACE
            resource["name"] = table_space
            resource["parentId"] = self.database_id
            resource["parentName"] = self.database_name
            resource["extendInfo"] = ""
            table_spaces_list.append(resource)
        params = {"resourceList": table_spaces_list}
        return params

